
package net.atremmedia.gwt.actionjava.examples.bitmap.samples;

import net.atremmedia.gwt.actionjava.examples.AJExample;
import net.atremmedia.gwt.actionjava.examples.frame.AJExampleOverview;
import actionjava.anim.Anim;
import actionjava.anim.config.Manifest;
import actionjava.display.Bitmap;
import actionjava.display.BitmapData;
import actionjava.display.Graphics;
import actionjava.display.Shape;
import actionjava.display.Sprite;
import actionjava.geom.Color;
import com.google.gwt.user.client.Timer;

public class BitmapExample4 extends AJExample
{
	public static final String NAME = "BitmapExample 4";
	public static final String DESCRIPTION = "Description";
	public static final String EXAMPLE_SRC = "https://code.google.com/p/gwt-actionjava/source/browse/trunk/aj-examples/aj-examples-bitmap/src/main/java/net/atremmedia/gwt/actionjava/examples/bitmap/samples/BitmapExample4.java";

	private Bitmap testBitmap;
	private Shape testShape;
	private Sprite testSprite;
	private Timer tweenTimer;

	public BitmapExample4(AJExampleOverview base)
	{
		super(NAME, DESCRIPTION, EXAMPLE_SRC, base);
	}

	@Override
	public void run()
	{
		testSprite = new Sprite();
		testSprite.setX(400);
		testSprite.setY(150);

		testShape = new Shape();
		testShape.setX(0);
		testShape.setY(-75);
		Graphics graph = testShape.getGraphics();
		graph.beginStroke("#000");
		graph.beginFill(Color.getRGBA(0xFF0000, 1));
		try {
			graph.decodePath("AumXSIo088IXexxIXXSAIpEc2g");
		} catch (Exception e) {
			e.printStackTrace();
		}
		graph.closePath();

		testBitmap = new Bitmap(new BitmapData("img/bitmapExample/testImg2.jpg"));
		testBitmap.setX(0);
		testBitmap.setY(0);
		testBitmap.setMask(testShape);

		testSprite.addChild(testBitmap);
		addChild(testSprite);

		animate();
		initTimer();
	}

	private void initTimer()
	{
		tweenTimer = new Timer()
		{
			@Override
			public void run()
			{
				animate();
			}
		};
		tweenTimer.scheduleRepeating(3100);
	}

	private void animate()
	{
		Anim.tween(new Manifest(testSprite, 3, getRandomEase())
		{
			@Override
			protected void configure()
			{
				fromTo(X, 0, getRandomX());
				fromTo(Y, 0, getRandomY());
			}
		});
	}

	private double getRandomX()
	{
		double x = getRandomNumber(100, 700);
		if(Math.abs(testSprite.getX() - x) < 200) {
			x += (x < testSprite.getX()) ? -200 : 200;
			x = (x < 100) ? 100 : x;
			x = (x > 700) ? 700 : x;
		}
		return x;
	}

	private double getRandomY()
	{
		double y = getRandomNumber(100, 700);
		if(Math.abs(testSprite.getY() - y) < 200) {
			y += (y < testSprite.getY()) ? -200 : 200;
			y = (y < 100) ? 100 : y;
			y = (y > 700) ? 700 : y;
		}
		return y;
	}

	@Override
	public void destroy()
	{
		super.destroy();
		tweenTimer.cancel();
	}
}
